﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using CommunitySystemModel;
using System.Data;

namespace CommunitySystem.BO.SystemManager
{
    public class RoleMenuBO
    {
        public ObservableCollection<RoleMenu> GetRoleMenu(int RoleID)
        {
            ObservableCollection<RoleMenu> rights = new ObservableCollection<RoleMenu>();
            string sql = string.Format(@"select m.ID as MenuID, m.Title, m.[Target], m.[Index], m.PID, m.icon, rm.ID as RoleMenuID, rm.RoleID   from MenuItem m
left join RoleMenu rm on (rm.RoleID = {0} or rm.ID is null) and rm.MenuID = m.ID
order by m.[Index]
", RoleID);
            DataSet ds = AccessHelper.GetInstance().ExcuteDataSet(sql);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                rights.Add(RoleMenu.FillEntity(dr));
            }
            return rights;
        }

        public bool UpdateRoleMenu(ObservableCollection<RoleMenu> rms)
        {
            string sql = string.Empty;
            string insert = "insert into RoleMenu(RoleID, MenuID)";
            if (rms.Where(c => c.RoleID > 0 && (c.ID == 0 || c.ID == null)).Count() > 0)
            {
                //新增的
                foreach (RoleMenu rm in rms.Where(c => c.RoleID > 0 && (c.ID == 0 || c.ID == null)))
                {
                    insert += "   select " + rm.RoleID + ", " + rm.MenuID + "  union";
                }
                insert = insert.TrimEnd(new char[] { 'u', 'n', 'i', 'o', 'n' });
                insert += ";";
                sql += insert;
            }
            foreach (RoleMenu rm in rms.Where(c => (c.RoleID == 0 || c.RoleID == null) && c.ID > 0))//删除的
            {
                sql += "    delete RoleMenu where id = " + rm.ID;
            }
            if(!string.IsNullOrEmpty(sql))
                AccessHelper.GetInstance().ExecuteNonQuery(sql);
            return true;
        }

        //public T? GetValueForDS<T>(object value)
        //{
        //    if (value != null)
        //        return (T)value;
        //    else return null;
        //}
    }
}
